import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author Tsarev Oleg<br/>
 *		   <b>mail:</b> tsarev.oi@mail.ru<br/>
 *         <b>date:</b> 09.08.2010<br/>
 *         <b>time:</b> 17:25:29
 *
 */
public class Builder {

	public static void main(String[] args) throws IOException {
		if (args.length<3) {
			throw new RuntimeException("Not enought parameters...");
		}
		
		File source = new File(args[0]);
		File target = new File(args[1]);
		String param = args[2];
		String[] buildKey = param.split("[|]");

		if (source.exists()) {
			target.createNewFile();
			BufferedReader fr = new BufferedReader(new FileReader(source));
			BufferedWriter fw = new BufferedWriter(new FileWriter(target));
			
			Boolean writeKey = true;
			Boolean changeKey = false;
			Integer instCounter = 0;
			String line;
			while ((line=fr.readLine())!=null) {
				
				if (line.trim().contains("/*builder-open key=")) {
					instCounter++;
					if (instCounter == 1) {
						String[] inst = line.split("\"");
						if (inst.length==3) {
							
								System.out.println("Searching "+param+" in "+inst[1]+"...");
								String[] keys = inst[1].split("[|]");
								if (isIn(buildKey,keys)) {
									writeKey = true;
								} else {
									writeKey = false;
								}
	
						} else {
							throw new RuntimeException("Source file conteins bad build instruction...");
						}
					}
				} else if (line.trim().contains("/*builder-close")) {
					instCounter--;
					if (instCounter == 0) {
						changeKey = true;
					}
				}
				if (writeKey) {
					fw.write(line);
					fw.newLine();
				}
				if (changeKey) {
					writeKey = true;
					changeKey = false;
				}
			}
			 
			fw.flush();
			fw.close();
			fr.close();
			
		} else {
			throw new RuntimeException("Source file not exists...");
		}

	}

	private static boolean isIn(String[] buildKey, String[] keys) {
		for (int i = 0,len = keys.length; i < len; i++) {
			for (int j = 0,lens = buildKey.length; j < lens; j++) {
				if (buildKey[j].equals(keys[i])) {
					return true;
				}
			}
		}
		return false;
	}

}
